package serverwork;

import com.sw.server.handthreadpool.RequestProcess;
import com.sw.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author sw
 * @project minicat
 * @description 自定义启动及初始化
 * @date 2020/4/30 12:49
 */
public class CusBootStrap {
    private static  final String DEFAULT_PORT="8080";

    private List<ApplicationInfo> applicationInfos=new ArrayList<>();
    /****
     * 参照应颠老师课程
     * 1.解析应用信息 此时读取的应用是编译后的class文件
     */

    public static void main(String[] args) throws DocumentException {
        CusBootStrap cusBootStrap=new CusBootStrap();
        //初始化配置信息
        //第一步 从配置文件中取出当前服务器部署的应用信息 默认是server.xml
        //按照tomcat源文件配置 多个项目 是在</Server> 标签下，配置多个service 标签
        cusBootStrap.loadApplicationInfo();
        //解析每个应用下的servlet路径
        cusBootStrap.initApplicationServletPath();
        cusBootStrap.start();

    }

    /**
     * 初始化每个应用下的servlet路径
     */
    private void initApplicationServletPath() {
        for(ApplicationInfo applicationInfo:applicationInfos) {
            String webapps = applicationInfo.getAppPath();
            File[] files = new File(webapps).listFiles(File::isDirectory);
            if (files != null) {
                for (File file : files) {
                    if(file.getName().equalsIgnoreCase("WEB-INF")){
                        initServletUrlPattern(file.getPath(),applicationInfo);
                    }

                }
            }
        }
    }

    /**
     *
     * @param path
     * @param applicationInfo
     */
    private void initServletUrlPattern(String path,ApplicationInfo applicationInfo){
        String webPath= path + "/web.xml";
        Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = new FileInputStream(new File(webPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                // 获取对象路径
                URL classesFile = new URL("file:" + path + "/classes/");
                URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{classesFile});
                Class<?> aClass = urlClassLoader.loadClass(servletClass);
                HttpServlet o = (HttpServlet) aClass.newInstance();
                //urlPattern 带上项目名称
                urlPattern="/"+applicationInfo.getAppName()+urlPattern;
                servletMap.put(urlPattern, o);
            }
            applicationInfo.setServerletMap(servletMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化应用配置信息
     */
    private void loadApplicationInfo() throws DocumentException {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader=new SAXReader();
        //获取文件路信息
        Document document = saxReader.read(resourceAsStream);
        //得到server 节点
        Element rootElement = document.getRootElement();
        //得到service节点信息
        List<Element> serviceElements = rootElement.selectNodes("service");
        //   解析应用配置
        for (int i = 0; i <serviceElements.size() ; i++) {
            //获取配置的应用信息
            Element serviceElement = serviceElements.get(i);
            //获取应用配置的端口
            String port = serviceElement.selectSingleNode("connectot").getStringValue();
            //如果端口号没有配置，就默认8080
            port=port==null?DEFAULT_PORT:port;
            //解析应用信息
            Element appElement = (Element) serviceElement.selectSingleNode("Engine").selectSingleNode("host");
            //访问ip
            String ipName = appElement.attributeValue("name");
            ipName=ipName==null?"localhost":ipName;
            //应用配置路径
            String appAboslutePath=appElement.attributeValue("appBase");
            //解析应用具体信息
           String appName=appAboslutePath.substring(appAboslutePath.lastIndexOf("/")+1,appAboslutePath.length());
           //拼装访问路径
            String accessPath="http://"+ipName+":"+port+"/"+appName;
            //解析应用下面的配置文件，及路径信息
            ApplicationInfo applicationInfo=new ApplicationInfo(port,ipName,appName,appAboslutePath,accessPath);
            applicationInfos.add(applicationInfo);
        }

    }

    /**
     * 创建服务启动
     */
    private void start() {
        //定义线程池
        int corePoolSize=10;//线程池初始化大小
        int maximumPoolSize=50;//最大
        long keepAliveTime=10;
        TimeUnit unit=TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory= Executors.defaultThreadFactory();
        RejectedExecutionHandler handler=new  ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(corePoolSize,maximumPoolSize,
                keepAliveTime,unit,workQueue,threadFactory,handler);
        /**
         * 浏览器访问http://localhost:8080
         */
        try {


            //动态资源
                //有多少个应用服务就初始化多少个socket连接 共用一个线程池
                for(ApplicationInfo applicationInfo:applicationInfos) {
                    int port=Integer.valueOf(applicationInfo.getPort());
                    ServerSocket serverSocket=new ServerSocket(port);
                    new SocketWork(serverSocket,threadPoolExecutor,applicationInfo).start();
                }

        }catch (Exception e){
            System.out.println();
        }
    }
}
